﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Common;

namespace ConsoleApp
{
    class Program
    {
        private static string baseUrl = "http://localhost/selfhost/api/contacts";

        static void Main(string[] args)
        {
            Process();
            Console.Read();
        }

        private async static void Process()
        {
            HttpClient httpClient = new HttpClient();
            ListContacts(httpClient);

            // 添加新联系人
            Contact contact = new Contact { Name = "王五", PhoneNo = "1233432434", EmailAddress = "dfdf@163.com" };
            await httpClient.PostAsJsonAsync<Contact>(baseUrl, contact);
            Console.WriteLine("添加新联系人：王五");
            ListContacts(httpClient);

            // 修改现有的某个联系人
            HttpResponseMessage response = await httpClient.GetAsync(baseUrl + "/001");
            contact = (await response.Content.ReadAsAsync<IEnumerable<Contact>>()).First();
            if(contact != null)
            {
                contact.Name = "赵六";
                contact.EmailAddress = "fdfad@qq.com";
                await httpClient.PutAsJsonAsync<Contact>(baseUrl, contact);
                Console.WriteLine("修改联系人“001”信息：");
                ListContacts(httpClient);
            }

            // 删除现有的某个联系人
            await httpClient.DeleteAsync(baseUrl + "/002");
            Console.WriteLine("删除联系人“002”:");
            ListContacts(httpClient);
        }

        private async static void ListContacts(HttpClient httpClient)
        {
            HttpResponseMessage response = await httpClient.GetAsync(baseUrl);
            IEnumerable<Contact> contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>();
            Console.WriteLine("当前联系人列表：");

            foreach (Contact item in contacts)
            {
                // {0,-6}: 0为变量占位，-6为6个字宽并左对齐
                Console.WriteLine("{0,-6}{1,-6}{2,20}{3,-10}",
                    item.Id, item.Name, item.EmailAddress, item.PhoneNo);
            }
            Console.WriteLine();
        }
    }
}
